from typing import Dict
from metric_reader import MetricReader
from sysom_utils import SysomFramework
from lib.metric_type.capacity import Level, CapacityMetric
from lib.metric_type.metric_type import DiagnoseInfo


class NodeFdUtil(CapacityMetric):
    def __init__(self, metric_reader: MetricReader, metric_settings,
                 level: Level):
        super().__init__(metric_reader, metric_settings, level)

    def _collect_process_metric(self):
        return self._usage_total_process(is_avaliable=False)

    def construct_diagnose_req(
            self, diagnose_info: DiagnoseInfo) -> Dict[str, str]:
        threshold = "80"
        command = "sysak sysctl " + "fd " + str(threshold)

        return {
            "service_name": self.settings.alarm.service_name,
            "instance": diagnose_info.instance.split(":")[0],
            "command": command,
            "channel": "ssh",
        }

    def process_diagnose_req(self, diagnose_info: DiagnoseInfo, data_dict):
        result = data_dict["CommandResult"]["data"][0]["value"]
        lines = result.split("\n")[1:-1]
        
        SysomFramework.alarm_action("ADD_ANNOTATION", {
            "alert_id": diagnose_info.alarm_id,
            "annotations": {
                "节点fd使用量top10进程": lines,
                "修复建议": [
                    "1.重启进程释放其占用的fd",
                    "2.通过ulimit调整进程的fd上限",
                    "3.调整系统的全局fd上限",
                    "4.检查以上进程是否存在fd泄露"
                ]
            }
        })
